package com.jhws.business.repair.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.business.repair.bo.Repair;
import com.jhws.business.repair.bo.RepairConstant;
import com.jhws.business.repair.bo.RepairUpdateData;
import com.jhws.common.base.bo.Global;
import com.jhws.common.Page;
import com.jhws.core.dataUpdate.service.DataUpdateService;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@SuppressWarnings("Duplicates")
@Service
public class RepairService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private ITblUserDimService userDimService;
    @Resource
    private ITblOwnerDimService ownerDimService;
    @Resource
    private DataUpdateService updateService;
    @Resource
    private OSSClientService ossClientService;

    /**
     * 保存报修信息
     *
     * @param repair 报修信息
     * @return id
     */
    public long saveRepair(Repair repair) throws Exception {
        Date date = new Date();
        repair.setCommitTime(date);
        repair.setLastModifyTime(date);
        BaseDao.h().save(repair);
        TblOwnerDimBo owner = ownerDimService.findTblOwnerDimById(repair.getOwnerCode());
        if (owner != null) {
            updateService.update(date.getTime(), RepairUpdateData.REPAIR, owner.getOwnerMob(), true);
        }
        return repair.getId();
    }

    /**
     * 分页报修反馈信息
     *
     * @param param map
     * @return
     */
    public Map<String, Object> findRepairListPage(Map param) {
        String whereClause = "1=1 ";
        String state = MapUtils.getString(param, "state", "");
        if (StringUtils.isNotEmpty(state)) {
            whereClause += " and state = '" + state + "'";
        }
        String commCode = MapUtils.getString(param, "commCode", "");
        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code = '" + commCode + "'";
        } else if (!SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            TblUserDimBo userBo = userDimService.currentUser();
            whereClause += " and comm_code in (" + userDimService.getUserCommsSqlStr(userBo) + ")";
        }
        String sql = "select * from comm_repair where " + whereClause;
        sql += " order by commit_time desc";
        Map<String, Object> result = new HashMap<>();
        Page p = BaseDao.queryPage(sql, Map.class);
        List<Map<String, Object>> list = p.getList();
        for (Map<String, Object> map : list) {
            int type = (int) map.get("type");
            Object objUrl = map.get("image_urls");
            List<String> urls = (objUrl == null || StringUtils.isEmpty(objUrl.toString())) ? new ArrayList<>() : JSON.parseArray(objUrl.toString(), String.class);
            List<String> ossUrls = new ArrayList<>();
            for (String url : urls) {
                ossUrls.add(ossClientService.getUrl(url, false));
            }
            map.replace("image_urls", ossUrls);
            map.replace("type", RepairConstant.REPAIR_TYPE.getName(type));
        }
        result.put("list", p.getList());
        result.put("size", p.getTotalNumber());
        result.put("ret_code", 1);
        return result;
    }

    /**
     * 用于api查询接口
     *
     * @param state
     * @param ownerCode
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> queryRepairListApi(int state, String ownerCode) throws Exception {
        return queryRepairListUpdated(state, ownerCode, null);
    }

    public List<Map<String, Object>> queryRepairListUpdated(int state, String ownerCode, Long time) throws Exception {
        String sql = "SELECT" + " a.id, a.content, a.commit_time, a.detailed_addr, a.image_urls, a.state,"
                + "	a.treatment_result, a.repair_per, a.repair_per_phone, a.type FROM comm_repair a WHERE is_delete = '0' ";

        if (time != null)
            sql += " and a.timestamp > '" + time + "'";

        TblOwnerDimBo ownerDimBo = ownerDimService.findTblOwnerDimById(ownerCode);
        if (ownerDimBo.getApplyType() == OwnerConstant.OWNER_TYPE_PROPERTY_MANAGER) {
            sql += " and a.comm_code='" + ownerDimBo.getCommCode() + "'";
        } else {
            sql += " and a.owner_code='" + ownerCode + "'";
        }

        if (state == RepairConstant.REPAIR_STATE_UNTREATED) {
            sql += " and a.state = '" + state + "'";
        } else if (state == RepairConstant.REPAIR_STATE_COMPLETE || state == RepairConstant.REPAIR_STATE_ACCEPTED) {
            sql += " and (a.state = '" + RepairConstant.REPAIR_STATE_COMPLETE + "' or a.state='" + RepairConstant.REPAIR_STATE_ACCEPTED + "' )";
        }
        sql += " order by a.commit_time desc";
        List<Map<String, Object>> list = BaseDao.j().queryForList(sql);
        for (Map<String, Object> map : list) {
            int type = (int) map.get("type");
            Object objUrl = map.get("image_urls");
            List<String> urls = (objUrl == null || StringUtils.isEmpty(objUrl.toString())) ? new ArrayList<>() : JSON.parseArray(objUrl.toString(), String.class);
            List<String> ossUrls = new ArrayList<>();
            for (String url : urls) {
                ossUrls.add(ossClientService.getUrl(url, false));
            }
            map.replace("image_urls", ossUrls);
            map.replace("type", RepairConstant.REPAIR_TYPE.getName(type));
        }
        return list;
    }

    /**
     * 获取报修信息数量
     *
     * @param where
     * @return
     */
    public int findRepairCount(String where) {
        String sql = "select count(*) as sum from comm_repair " + where;
        return BaseDao.j().queryForObject(sql, Integer.class);
    }

    /**
     * 更新报修信息
     *
     * @param set
     * @param where
     */
    public void updateRepair(String set, String where) {
        String sql = "update comm_repair " + set + where;
        BaseDao.j().execute(sql);
    }

    /**
     * 删除报修
     */
    public void deleteRepair(Repair repair) {
        BaseDao.h().delete(repair);
    }

    /**
     * 删除报修
     */
    public void deleteRepairApi(long id) {
        String sql = "update comm_repair set is_delete = '1' where id = '" + id + "'";
        BaseDao.j().execute(sql);
    }
}
